import { useEffect, useRef, useState } from "react";
import { useSelector, useDispatch } from 'react-redux'
import type { RootState } from '../../store/store'
import { setCurrentCity } from '../../store/UseStateList'
import { useAMapLocation } from '../../utils/useAMapLocation'
import style from "./index.module.css";
import { NoticeBar, NavBar, CapsuleTabs } from "antd-mobile";
import { ResultPage, Card, Button, Input, PullToRefresh } from "antd-mobile";
import request from "../../api/request";
import { Image, List } from "antd-mobile";
import { InfiniteScroll } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { SearchOutline } from "antd-mobile-icons";
import { hasFeaturePermission, getPermissionMessage } from "../../utils/permission";
import { Toast } from "antd-mobile";
// Use public assets via absolute path
const Image0 = "/yuyue.jpg";
const Image1 = "/jisu.jpg";
const Image2 = "/fuzhen.jpg";
const Img1 = "/1103.jpg";
const Img2 = "/1203.jpg";
const Img3 = "/1303.jpg";
const Img4 = "/1403.jpg";
// const Img5 = "/1506.jpg";
type Doctor = {
  doctorstate: string;
  socolv: string;
  doctorcity: string;
  doctorimage: string;
  doctorflag: number;
  doctorprice: number;
  doctorid: number;
  doctorgood: number;
  doctorname: string;
  doctoradministre?: string;
  socoadmin?: string;
  doctortime?: number;
  texttype?: string;
  texttitle?: string;
  textdise?: string;
  textimage?: string;
  restorativesimage?: string;
  restorativesname?: string;
  restorativesprice?: number;
    restorativesid?: number;
  textid?: number;
    textaudio?: string;
};

function Index() {
  const [doctorList, setDoctorList] = useState<Doctor[]>([]);
  const pageCode = 1;
  const pageSize = 16;
  const navigate = useNavigate();
  const pageCode1 = 1;
  const pageSize1 = 16;
  const dispatch = useDispatch();
  
  const currentCity = useSelector((state: RootState) => state.UseStateList.currentCity)
  
  // 定位相关状态
  const { city, loading: locationLoading, getLocation } = useAMapLocation();

  // 初始化定位
  useEffect(() => {
    const initLocation = async () => {
      try {
        await getLocation();
      } catch (error) {
        console.error('定位失败:', error);
        // 定位失败时保持默认城市，不显示错误信息给用户
      }
    };
    
    // 只有在当前城市为默认值（广州）时才进行定位
    if (currentCity === '广州') {
      initLocation();
    }
  }, [getLocation, currentCity]);

  // 当定位成功获取到城市信息时，更新Redux store
  useEffect(() => {
    if (city && city !== currentCity) {
      dispatch(setCurrentCity(city));
    }
  }, [city, currentCity, dispatch]);

  const [restorativelist, setRestorativelist] = useState<Doctor[]>([]);
  const [booklist, setBooklist] = useState<Doctor[]>([]);
  const [pageCode2, setPageCode2] = useState(1);
  const pageSize2 = 10;
  const [hasMore, setHasMore] = useState(true);
  const [isCompact, setIsCompact] = useState(false);
  const scrollRafRef = useRef<number | null>(null);
  const [currentPlayingAudio, setCurrentPlayingAudio] = useState<HTMLAudioElement | null>(null);
  const lastCompactRef = useRef<boolean>(false);
  const mountedRef = useRef<boolean>(true);
  const compactTimerRef = useRef<number | null>(null);

  useEffect(() => {
    mountedRef.current = true;
    const THRESHOLD = 150;
    const onScroll = () => {
      if (scrollRafRef.current !== null) return;
      scrollRafRef.current = window.requestAnimationFrame(() => {
        scrollRafRef.current = null;
        if (!mountedRef.current) return;
        const y = window.scrollY || document.documentElement.scrollTop || 0;
        const nextCompact = y > THRESHOLD;
        if (nextCompact !== lastCompactRef.current) {
          // 下拉进入紧凑模式加1秒延迟，回到顶部立即还原
          if (nextCompact) {
            if (compactTimerRef.current !== null) {
              window.clearTimeout(compactTimerRef.current);
            }
            compactTimerRef.current = window.setTimeout(() => {
              if (!mountedRef.current) return;
              lastCompactRef.current = true;
              setIsCompact(true);
              compactTimerRef.current = null;
            }, 300);
          } else {
            if (compactTimerRef.current !== null) {
              window.clearTimeout(compactTimerRef.current);
              compactTimerRef.current = null;
            }
            lastCompactRef.current = false;
            setIsCompact(false);
          }
        }
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    // 初始化一次，避免首次渲染状态不对
    onScroll();
    return () => {
      mountedRef.current = false;
      window.removeEventListener("scroll", onScroll);
      if (scrollRafRef.current !== null) {
        window.cancelAnimationFrame(scrollRafRef.current);
        scrollRafRef.current = null;
      }
      if (compactTimerRef.current !== null) {
        window.clearTimeout(compactTimerRef.current);
        compactTimerRef.current = null;
      }
    };
  }, []);

  // 根据tab索引获取对应的医生数据切片
  const getDoctorsForTab = (tabIndex: number) => {
    const startIndex = tabIndex * 2;
    const endIndex = startIndex + 2;
    return doctorList.slice(startIndex, endIndex);
  };

  // 根据tab索引获取对应的药品数据切片
  const getRestorativesForTab = (tabIndex: number) => {
    const startIndex = tabIndex * 4;
    const endIndex = startIndex + 4;
    return restorativelist.slice(startIndex, endIndex);
  };

  // 医生列表展示组件
  const DoctorListComponent = ({ doctors }: { doctors: Doctor[] }) => (
    <div>
      <List>
        {doctors.length > 0 &&
          doctors.map((item, index) => (
            <List.Item
              key={index}
              onClick={() => goDoctorDetail(item.doctorid)}
              className={style.doctorCard}
              prefix={
                <Image
                  src={item.doctorimage}
                  className={style.avatar}
                  fit="cover"
                  width={48}
                  height={48}
                />
              }
              description={
                <div className={style.desc}>
                  <div className={style.hospitalLine}>{item.doctorcity}</div>
                  
                  <div className={style.tags}>
                    <span className={style.tag}>图文咨询</span>
                    <span className={style.tag}>电话咨询</span>
                    <span className={style.tag}>视频咨询</span>
                  </div>
                  <div className={style.expert}>
                    {item.socoadmin || item.doctoradministre}
                  </div>
                  <div className={style.stats}>
                    <span>
                      好评率
                      <span className={style.haoping}>
                        {((item.doctorflag || 0) * 100).toFixed(0)}
                      </span>
                      %
                    </span>
                    <span className={style.statDot}>|</span>
                    <span>
                      锦旗{" "}
                      <span className={style.haoping}>
                        {((item.doctorprice || 0) - 45).toFixed(0)}
                      </span>
                    </span>
                    <span className={style.statDot}>|</span>
                    <span>
                      浏览人数{" "}
                      <span className={style.haoping}>
                        {item.doctorid || 0}
                      </span>
                    </span>
                  </div>
                  <div className={style.bottomRow}>
                    <div className={style.priceBox}>
                      <span className={style.priceNumber}>
                        ￥{item.doctorgood || 0}起
                      </span>
                    </div>
                    <Button size="mini" color="primary">
                      问医生
                    </Button>
                  </div>
                </div>
              }
            >
              <div className={style.titleRow}>
                <span className={style.name}>{item.doctorname}</span>
                <div className={style.meta}>
                  <span className={style.badgePrimary}>{item.doctorstate}</span>
                  <span className={style.badgeLevel}>{item.socolv}</span>
                </div>
              </div>
            </List.Item>
          ))}
      </List>
    </div>
  );

  // 获取医生列表
  useEffect(() => {
    const fetchList = async () => {
      const res: { code: number; data: Doctor[] } = await request.get(
        "/api/doctor/list",
        {
          params: {
            pageCode: pageCode,
            pageSize: pageSize,
          },
        }
      );
      console.log("医生列表数据", res);
      if (res.code === 20000) {
        setDoctorList(res.data);
      }
    };
    fetchList();
  }, []);

  // 获取药品列表
  useEffect(() => {
    const getRestorativelist = async () => {
      const res: { code: number; data: Doctor[] } = await request.get(
        "/api/restorative/list",
        {
          params: {
            pageCode: pageCode1,
            pageSize: pageSize1,
          },
        }
      );
      console.log("药品列表数据", res);
      if (res.code === 200) {
        setRestorativelist(res.data);
      }
    };
    getRestorativelist();
  }, []);

  // 获取文章列表

  const getBooklist = async () => {
    const res: { code: number; data: Doctor[] } = await request.get(
      "/api/book/list",
      {
        params: {
          pageCode: pageCode2,
          pageSize: pageSize2,
        },
      }
    );
    console.log("文章列表", res);
    if (res.code === 20000) {
      setBooklist([...booklist, ...res.data]);
      setPageCode2(pageCode2 + 1);
    }
    if (res.data.length === 0) {
      setHasMore(false);
    }
  };

  useEffect(() => {
    getBooklist();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 跳转文章详情
  const goArtDetail = (id: number) => {
    navigate(`/ArtDetail/${id}`);
  };

  // 跳转医生详情
  const goDoctorDetail = (id: number) => {
    navigate(`/DoctorDetail/${id}`);
  };

  // 跳转药品详情
  const goMedicineDetail = () => {
    navigate(`/MedicineDetail`);
  };

  // 跳转我要买药订单
  const goSocoDetail = (id:number)=>{
    navigate(`/SocoDetail/${id}`)
  }

  // 事件委托处理音频播放
  const handleAudioPlay = (e: React.MouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡，避免触发父元素的点击事件
    
    const audioUrl = (e.currentTarget as HTMLElement).getAttribute('data-audio-url');
    if (audioUrl) {
      // 暂停当前正在播放的音频（如果存在）
      if (currentPlayingAudio && !currentPlayingAudio.paused) {
        currentPlayingAudio.pause();
      }
      
      // 创建新的音频元素并播放
      const audio = new Audio(audioUrl);
      setCurrentPlayingAudio(audio);
      
      audio.play().catch(error => {
        console.error('音频播放失败:', error);
        setCurrentPlayingAudio(null);
      });
      
      // 音频播放结束时清除状态
      audio.addEventListener('ended', () => {
        setCurrentPlayingAudio(null);
      });
      
      // 音频暂停时也清除状态
      audio.addEventListener('pause', () => {
        setCurrentPlayingAudio(null);
      });
    }
  };



  const demoLongText =
    "公告:1、自治区卫生热线0951-12320银川市政府热线0951-12320银川市政府热线0951-12345妙手互联网医院热线400-078-1000";
  return (
    <div className={style.homePage}>
      {/* 头部区域 */}
      <div className={`${style.head} ${isCompact ? style.headCompact : ""}`}>
        {isCompact ? (
          <div className={style.headRow}>
            <div className={style.iconsearch}>
              <SearchOutline
                className={style.icon}
                fontSize={18}
                style={{ padding: 1, color: "#75a6ff" }}
              />
              <Input
                onFocus={() => navigate("/Search")}
                style={{ fontSize: "12px" }}
                placeholder="搜索内容、医生、药品、疾病症状"
              />
            </div>
            <span className={style.headTitles} onClick={()=>navigate('/City')}>
              {locationLoading ? '定位中...' : currentCity}
            </span>
          </div>
        ) : (
          <>
            <div className={style.headTit}>
              <span className={style.headTitle}>
                <b>妙手医生</b> · 妙手互联网医院
              </span>
              <span className={style.headTitles} onClick={()=>navigate('/City')}>
                {locationLoading ? '定位中...' : currentCity}
              </span>
            </div>
            <div className={style.iconsearch}>
              <SearchOutline
                className={style.icon}
                fontSize={18}
                style={{ padding: 1, color: "#75a6ff" }}
              />
              <Input
                onFocus={() => navigate("/Search")}
                style={{ fontSize: "12px" }}
                placeholder="搜索内容、医生、药品、疾病症状"
              />
            </div>
          </>
        )}
        {/* <SearchBar className={style.indexsearch}  placeholder="搜索内容、医生、药品、疾病症状" /> */}
      </div>

      <PullToRefresh
        onRefresh={async () => {
          await new Promise((resolve) => setTimeout(resolve, 1000));
          window.location.reload();
        }}
        pullingText="下拉即可刷新"
        refreshingText="刷新中..."
      >
        <ResultPage.Card
          className={style.cardBox1}
          style={{ height: "100%", padding: 8 }}
        >
          <NoticeBar
            className={style.noticebar}
            content={demoLongText}
            color="alert"
          />
          <div className={style.card}>
            <Card 
              onClick={() => {
                if (hasFeaturePermission('预约挂号')) {
                  navigate('/Yuyue');
                } else {
                  Toast.show({ content: getPermissionMessage('预约挂号') });
                }
              }} 
              style={{ height: 130, width: 110, marginTop: 12 }}
            >
              <img
                src={Image0}
                style={{ width: "100%", height: "80%" }}
                alt=""
              />
              <p className={style.span_title}>预约挂号</p>
              <p className={style.span_content}>30w+专家入驻</p>
            </Card>

            <Card 
              style={{ height: 130, width: 110, marginTop: 12 }} 
              onClick={() => {
                if (hasFeaturePermission('极速问诊')) {
                  navigate('/Wenzhen');
                } else {
                  Toast.show({ content: getPermissionMessage('极速问诊') });
                }
              }}
            >
              <img
                src={Image1}
                style={{ width: "100%", height: "80%" }}
                alt=""
              />
              <p className={style.span_title}>极速问诊</p>
              <p className={style.span_content}>平均3分钟接诊</p>
            </Card>
            <Card 
              style={{ height: 130, width: 110, marginTop: 12 }} 
              onClick={() => {
                if (hasFeaturePermission('复诊开方')) {
                  navigate('/Fuzhen');
                } else {
                  Toast.show({ content: getPermissionMessage('复诊开方') });
                }
              }}
            >
              <img
                src={Image2}
                style={{ width: "100%", height: "80%" }}
                alt=""
              />
              <p className={style.span_title}>复诊开方</p>
              <p className={style.span_content}>慢病例方送到家</p>
            </Card>
          </div>

          <div className={style.card_sp}>
            <span>
              <img src={Img1} alt="" />
              <p>问专家</p>
            </span>
            <span>
              <img src={Img2} alt="" />
              <p>开药门诊</p>
            </span>
            <span>
              <img src={Img3} alt="" />
              <p>义诊直播</p>
            </span>
            <span>
              <img src={Img4} alt="" />
              <p>健康科普</p>
            </span>
            <span>
              <img src={Img4} alt="" />
              <p>商城买药</p>
            </span>
          </div>
        </ResultPage.Card>

        <ResultPage.Card
          className={style.cardBox1}
          style={{ marginTop: 20, height: "100%" }}
        >
          <NavBar
            backIcon={false}
            left={<h3>我要问专家</h3>}
            right={<p onClick={() => navigate("/TalkDoctor")}>更多{`>`}</p>}
          ></NavBar>
          <div>
            <CapsuleTabs className={style.capsuleTabs}>
              <CapsuleTabs.Tab title="妇产科" key="fruits">
                <DoctorListComponent doctors={getDoctorsForTab(0)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="儿科" key="vegetables">
                <DoctorListComponent doctors={getDoctorsForTab(1)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="皮肤科" key="animals">
                <DoctorListComponent doctors={getDoctorsForTab(2)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="血心管内科" key="Vasculocardiology ">
                <DoctorListComponent doctors={getDoctorsForTab(3)} />
              </CapsuleTabs.Tab>

              <CapsuleTabs.Tab title="呼吸内科" key="respiratory">
                <DoctorListComponent doctors={getDoctorsForTab(4)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="消化内科" key="gastroenterology">
                <DoctorListComponent doctors={getDoctorsForTab(5)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="中医科" key="中医科">
                <DoctorListComponent doctors={getDoctorsForTab(6)} />
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="口腔科" key="stomatology ">
                <DoctorListComponent doctors={getDoctorsForTab(7)} />
              </CapsuleTabs.Tab>
            </CapsuleTabs>
          </div>
          <span className={style.more} onClick={() => navigate("/TalkDoctor")}>
            查看此科室更多医生
          </span>
        </ResultPage.Card>

        <ResultPage.Card
          className={style.cardBox1}
          style={{ marginTop: 20, height: "100%" }}
        >
          <NavBar
            backIcon={false}
            left={<h3>我要买药</h3>}
            right={<p onClick={() => goMedicineDetail()}>更多{`>`}</p>}
          ></NavBar>
          <div>
            <CapsuleTabs className={style.capsuleTabs}>
              <CapsuleTabs.Tab title="皮肤用药" key="fruit">
                <div className={style.yaos}>
                  {getRestorativesForTab(0).length > 0 &&
                    getRestorativesForTab(0).map((item, index) => (
                      <div key={index} className={style.yao} onClick={()=> item.restorativesid != null ? goSocoDetail(item.restorativesid) : void 0}>
                        <img src={item.restorativesimage} alt="" />


                        <div className={style.OTCp}>
                          <p> 
                            <span>OTC</span>
                          {item.restorativesname}
                          </p>
                        </div>


                        <span className={style.price}>
                          ￥{item.restorativesprice}
                        </span>
                      </div>
                    ))}
                </div>
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="男科用药" key="vegetable">
                <div className={style.yaos}>
                  {getRestorativesForTab(1).length > 0 &&
                    getRestorativesForTab(1).map((item, index) => (
                      <div key={index} className={style.yao}>
                        <img src={item.restorativesimage} alt="" />
                        <div className={style.OTCp}>
                          <span>OTC</span>
                          <p>{item.restorativesname}</p>
                        </div>
                        <span className={style.price}>
                          ￥{item.restorativesprice}
                        </span>
                      </div>
                    ))}
                </div>
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="妇科用药" key="animal">
                <div className={style.yaos}>
                  {getRestorativesForTab(2).length > 0 &&
                    getRestorativesForTab(2).map((item, index) => (
                      <div key={index} className={style.yao}>
                        <img src={item.restorativesimage} alt="" />
                        <div className={style.OTCp}>
                          <span>OTC</span>
                          <p>{item.restorativesname}</p>
                        </div>
                        <span className={style.price}>
                          ￥{item.restorativesprice}
                        </span>
                      </div>
                    ))}
                </div>
              </CapsuleTabs.Tab>
              <CapsuleTabs.Tab title="儿科用药" key="Vasculocardiolog ">
                <div className={style.yaos}>
                  {getRestorativesForTab(3).length > 0 &&
                    getRestorativesForTab(3).map((item, index) => (
                      <div key={index} className={style.yao}>
                        <img src={item.restorativesimage} alt="" />
                        <div className={style.OTCp}>
                          <span>OTC</span>
                          <p>{item.restorativesname}</p>
                        </div>
                        <span className={style.price}>
                          ￥{item.restorativesprice}
                        </span>
                      </div>
                    ))}
                </div>
              </CapsuleTabs.Tab>
            </CapsuleTabs>
          </div>
          <span className={style.more} onClick={() => goMedicineDetail()}>
            查看此分类下更多药品
          </span>
        </ResultPage.Card>

        <Card className={style.cardBox1}>
          <div className={style.recommend}>
            <h3>为你推荐</h3>
            <div className={style.recommendList}>
              {booklist.length > 0 &&
                booklist.map((item, index) => (
                  <div
                    key={index}
                    className={style.itemlist}
                    onClick={() => {
                      if (item.textid != null) goArtDetail(item.textid);
                    }}
                  >
                    <div className={style.itemimg}>
                      <img src={item.doctorimage} alt="" />

                      <div className={style.itemright}>
                        <span>{item.doctorname}</span>
                        <div className={style.item_title}>
                          <span>{item.doctorstate}</span>
                          <span style={{ marginLeft: 5 }}>
                            {item.doctortime || 0}人浏览
                          </span>
                        </div>
                      </div>
                    </div>

                    <div >
                      <div className={style.itemtext}>
                        <span className={style.spanstyle}>{item.texttype}</span>
                        <span className={style.spanstyles}>
                          {item.texttitle}
                        </span>
                      </div>

                      <div className={style.itemTextImg}>
                        {item.texttype === "语音" && item.textaudio && (
                          <div 
                            className={style.audioPlayButton}
                            data-audio-url={item.textaudio}
                            onClick={(e) => handleAudioPlay(e)}
                            style={{
                              backgroundImage: `url(${item.doctorimage})`,
                              backgroundSize: 'cover',
                              backgroundPosition: 'center',
                              position: 'relative',
                              width: '80px',
                              height: '60px',
                              borderRadius: '8px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              cursor: 'pointer',
                              marginRight: '12px',
                              flexShrink: 0
                            }}
                          >
                            <span 
                              className={style.playIcon}
                              style={{
                                color: 'white',
                                fontSize: '24px',
                                textShadow: '0 0 5px rgba(0,0,0,0.5)',
                                backgroundColor: 'rgba(0,0,0,0.3)',
                                borderRadius: '50%',
                                width: '36px',
                                height: '36px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                              }}
                            >
                              🎧
                            </span>
                          </div>
                        )}
                        <div >
                          <p className={style.textlist} style={{ margin: 0, lineHeight: '1.4' }}>{item.textdise}</p>
                        </div>
                      </div>

                    </div>
                  </div>
                ))}
            </div>
            <InfiniteScroll loadMore={getBooklist} hasMore={hasMore} />
          </div>
        </Card>

        {/* </ResultPage> */}
      </PullToRefresh>
    </div>
  );
}

export default Index;
